package com.bicon.life.core.base.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;
import java.util.Map.Entry;


/**
 * Created by lenovo on 2017/2/21.
 */
public class MD5Util {


    /**
     * 参数排序并加密
     * @author tandk
     * @date 2017-2-20 下午2:27:21
     * @param
     * @throws ClassNotFoundException
     * @throws SecurityException
     * @throws NoSuchMethodException
     */
    public static boolean sortAndMd5ForObject(String saltVal, HttpServletRequest request, Object o) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, IllegalAccessException{
            String md5Val = request.getParameter("md5Val");
            String timestampVal = request.getParameter("timestampVal");
            String randomVal = request.getParameter("randomVal");
            Map<String,Object> map = new HashMap<String,Object>();
            Class clazz = (Class)o.getClass();
            //得到类中的所有属性集合
            Field[] fs = clazz.getDeclaredFields ();
            for(int i = 0 ; i < fs. length ; i++){
                Field f = fs[i];
                f.setAccessible( true ); // 设置些属性是可以访问的
                Object val = f.get(o); // 得到此属性的值
                if(val != null){
                    map.put(f.getName().toLowerCase(), val);
                }
            }
            map.put("saltVal", saltVal);
            map.put("timestampVal", timestampVal);
            map.put("randomVal", randomVal);
            return sortAndMd5(md5Val, map);
    }



    /**
     * 参数排序并加密
     * @author tandk
     * @date 2017-2-20 下午2:27:21
     * @param request request
     * @throws ClassNotFoundException
     * @throws SecurityException
     * @throws NoSuchMethodException
     */
    public static boolean sortAndMd5ForParams(String saltVal, HttpServletRequest request){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("saltVal".toLowerCase(), saltVal);
            Map<String, String[]> parameterMap = request.getParameterMap();
            String md5Val = "";
            if(parameterMap != null){
                if(!parameterMap.isEmpty()){
                    Set<Entry<String, String[]>> set = parameterMap.entrySet();
                    Iterator<Entry<String, String[]>> it = set.iterator();
                    while (it.hasNext()) {
                        Entry<String, String[]> entry = it.next();
                        String key = entry.getKey();
                        String value = "";
                        for (String v : entry.getValue()) {
                            value = value+v;
                        }
                        if("md5Val".equals(key)){
                            md5Val = value;
                        }else if("timestampVal".equals(key)){
                            map.put("timestampVal".toLowerCase(), value);
                        }else if("randomVal".equals(key)){
                            map.put("randomVal".toLowerCase(), value);
                        }else{
                            map.put(key.toLowerCase(), value);
                        }
                    }
                }
            }
            return sortAndMd5(md5Val, map);
    }

    /**
     * 校验map排序加密公共方法
     * @author tandk
     * @param md5Val 待校验的md5值
     * @param map 待排序加密的参数map
     * @date 2017-2-21 下午1:01:23
     * @param
     * @return boolean
     */
    public static boolean sortAndMd5(String md5Val, Map<String,Object> map){
        List<Entry<String,Object>> list = new ArrayList<Entry<String,Object>>(map.entrySet());
        Collections.sort(list, new Comparator<Entry<String,Object>>(){
            @Override
            public int compare(Entry<String, Object> o1,
                               Entry<String, Object> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });
        StringBuffer sb = new StringBuffer();
        System.out.println("=============排序后================");
        for(Entry<String,Object> mapping : list){
            sb.append(mapping.getKey());
            sb.append("=");
            sb.append(mapping.getValue());
            sb.append("&");
            System.out.println(mapping.getKey()+"="+mapping.getValue());
        }
        String str = sb.toString();
        if(str.endsWith("&")){
            str = str.substring(0, str.length()-1);
        }
        String result = EncryptionUtil.getMD5Str(str);
        System.out.println("加密前：" + str);
        System.out.println("加密后：" + result);
        System.out.println(md5Val);
        System.out.println("md5Val.equals(result):"+md5Val.equals(result));
        return md5Val.equals(result);
    }
}
